# app/scheduler.py

from contextlib import asynccontextmanager
from fastapi import FastAPI
from apscheduler.schedulers.background import BackgroundScheduler
from app.utils.tasks.daily_job import run_my_3am_service  # 导入您的任务函数
from loguru import logger

# 创建一个后台调度器实例
scheduler_instance = BackgroundScheduler(timezone="Asia/Shanghai")

@asynccontextmanager
async def scheduler(app: FastAPI):
    """
    应用的定时任务管理器
    """
    logger.info("应用启动... 开始执行定时任务。")
    scheduler_instance.add_job(
        run_my_3am_service,
        trigger="cron",
        hour=3,
        minute=0,
        name="daily_3am_service"
    )
    scheduler_instance.start()
    logger.info("定时任务已添加并启动。")
    yield
    logger.info("应用关闭... 开始关闭定时任务。")
    scheduler_instance.shutdown()
    logger.info("调度器已关闭。")

__all__ = ['scheduler']
